package threadcoreknowledge.threadobjectclasscommonmethods;

import javax.jws.soap.SOAPBinding;

/**
 * @ClassName WaitNotifyReleaseOwnMonitor
 *  TODO 证明wait只释放当前的那把锁
 * @Author wushaopei
 * @Date 2021/4/19 23:42
 * @Version 1.0
 */
public class WaitNotifyReleaseOwnMonitor {

    private static volatile Object resourceA = new Object();
    private static volatile Object resourceB = new Object();

    public static void main(String[] args) {
        Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (resourceA){  // 拿到锁A
                    System.out.println("ThreadA got resourceA lock.");
                    synchronized (resourceB){  // 拿到锁B
                        System.out.println("ThreadA got resourceB lock.");
                        try {
                            System.out.println("ThreadA releases resourceA lock.");
                            resourceA.wait(); // 释放锁A
                        }catch (InterruptedException e){
                            e.printStackTrace();
                        }
                    }
                }
            }
        });
        Thread thread2 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(1000);
                }catch (InterruptedException e){
                    e.printStackTrace();
                }
                synchronized (resourceA){
                    System.out.println("ThreadB got resourceA lock.");
                    System.out.println("ThreadB tries to resourceB lock.");
                    synchronized (resourceB){
                        System.out.println("ThreadB got resourceB lock.");
                    }
                }
            }
        });
        thread1.start();
        thread2.start();
    }
}
